package com.cn.ccp.action.course;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;

import jxl.Sheet;
import jxl.Workbook;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.cn.ccp.action.BaseAction;
import com.cn.ccp.bean.CourseBean;
import com.cn.ccp.bean.CourseContentBean;
import com.cn.ccp.bean.CourseSettingBean;
import com.cn.ccp.bean.TrainingBean;
import com.cn.ccp.service.course.TrainingService.TraningScoreBean;
import com.cn.ccp.util.CCPContants;

public class CourseTrainingAction extends BaseAction {
	private Logger log = Logger.getLogger(CourseTrainingAction.class);
	//需要测试的课程list
	private List<CourseBean> courseTestList ;
	//显示对应测试课程章节需要测试的list
	private List<CourseContentBean> courseContentTestList ;
	//对应的试题list
	private List<TrainingBean> trainingList ;
	
	private TrainingBean trainingBean ;
	
	private boolean isCourseCome = false ;
	
	private String chapter_course_id ;
	//当前添加试题总分数
	private int traningCurrTotalScore = 0;
	private int traningTotalScore = 0;
	// 是否显示分数超出提示信息
	private boolean showErrorMsg = false; 
	//是显示添加试题按钮
	private boolean showAddButton = false; 
	
	private int courrCourseId = 0 ;
	
	private String type ;//类型： 1---为考试 2-----作业 3-----课程调查
	
	
	public String goAddTraining(){
		trainingBean = new TrainingBean();
		if(trainingList == null)
			trainingBean.setTraining_no("1");
		else 
			trainingBean.setTraining_no(""+(trainingList.size()+1));
		
		if(isCourseCome)
			trainingBean.setIs_chapter("0");
		else
			trainingBean.setIs_chapter("1");
		return EDIT ;
	}
	public String goUpdateTraining(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String id = varMap.get("id");
		trainingBean = getTrainingService().showBean(id);
		return EDIT ;
	}
	
	public void goDeleteTraining(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String id = varMap.get("id");
		getTrainingService().delete(Integer.parseInt(id));
		trainingList = getTrainingService().getCourseAll(chapter_course_id ,type);
		courseContentTestList = getCourseContentService().getTestChapterLis(courrCourseId);
		showAddButton = false; 
		TraningScoreBean bean = getTrainingService().checkTraningScoreIsSubmit(type,chapter_course_id);
		traningTotalScore = bean.getTotalScore() ;
		traningCurrTotalScore = bean.getTraningScore();
	}
	
	
	public String editTraining(){
		showErrorMsg = false;
		if(trainingBean.getTraining_contents() == null || trainingBean.getTraining_contents().equals("")){
			showMsg("training_contents", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(trainingBean.getTraining_refrence_answer() == null || trainingBean.getTraining_refrence_answer().equals("")){
			showMsg("training_refrence_answer", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(trainingBean.getTraining_score() == null || trainingBean.getTraining_score().equals("")){
			showMsg("training_score", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(!CCPContants.isNumber(trainingBean.getTraining_score())){
			showMsg("training_score", "training_page_score_error_1");
			return "";
		}
		trainingBean.setIs_chapter(type);
		/**
		 * 表示当前操作是判断题还是选择题
		 * 判断题标示： 1：[选择值0：错误/1：正确]
		 * 选择题标示：0：[A值描述]:[B值描述]:[C值描述]:[D值描述]
		 */
		JSONObject json = new JSONObject();
		json.put("type", trainingBean.getTraining_options_type());
		String optionVal = "" ;
		if(trainingBean.getTraining_options_type().equals("1")){
			//进行值是否选择判断
			if(trainingBean.getTraining_options_judgment() == null || trainingBean.getTraining_options_judgment().equals("")){
				showMsg("options_judgment", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			//判断题
//			optionVal = trainingBean.getTraining_options_type() +":"+trainingBean.getTraining_options_judgment();
//			if(trainingBean.getTraining_options_judgment().equals("0"))
//				trainingBean.setTraining_refrence_answer("B");
//			else
//				trainingBean.setTraining_refrence_answer("A");
		}else{
			//进行值是否选择判断
			if(trainingBean.getTraining_options_select_a() == null || trainingBean.getTraining_options_select_a().equals("")){
				showMsg("training_optionsA", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			if(trainingBean.getTraining_options_select_b() == null || trainingBean.getTraining_options_select_b().equals("")){
				showMsg("training_optionsB", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			if(trainingBean.getTraining_options_select_c() == null || trainingBean.getTraining_options_select_c().equals("")){
				showMsg("training_optionsC", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			if(trainingBean.getTraining_options_select_d() == null || trainingBean.getTraining_options_select_d().equals("")){
				showMsg("training_optionsD", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			//选择题
//			optionVal = trainingBean.getTraining_options_type() +":"+trainingBean.getTraining_options_select_a()
//																+":"+trainingBean.getTraining_options_select_b()
//																+":"+trainingBean.getTraining_options_select_c()
//																+":"+trainingBean.getTraining_options_select_d(); 
			json.put("a", trainingBean.getTraining_options_select_a());
			json.put("b", trainingBean.getTraining_options_select_b());
			json.put("c", trainingBean.getTraining_options_select_c());
			json.put("d", trainingBean.getTraining_options_select_d());
		}
		optionVal = json.toString();
		trainingBean.setTraining_options(optionVal);
		
		//检查成绩是否超过设置值                                                                              
		TraningScoreBean bean = getTrainingService().checkTraningScoreIsSubmit(type,chapter_course_id);
		traningTotalScore = bean.getTotalScore() ;
		if( trainingBean.getId() == 0){
			traningCurrTotalScore = bean.getTraningScore() + Integer.parseInt(trainingBean.getTraining_score());
		}else{
			TrainingBean tbean = getTrainingService().showBean(""+trainingBean.getId());
			traningCurrTotalScore = bean.getTraningScore() - Integer.parseInt(tbean.getTraining_score()) +  Integer.parseInt(trainingBean.getTraining_score());
		}
			
		if(traningCurrTotalScore > traningTotalScore){
//			showMsg("training_score", "course_page_course_submit_error_4");
			showErrorMsg = true ;
			return "";
		}
		if(traningTotalScore == traningCurrTotalScore)
			showAddButton = true ;
		else
			showAddButton = false ;
		
		boolean flag = false; 
		trainingBean.setChapter_course_id(chapter_course_id);
//		if(isCourseCome)
//			trainingBean.setIs_chapter("0");
//		else
//			trainingBean.setIs_chapter("1");
		if(trainingBean.getId() == 0 )
			flag = getTrainingService().sava(trainingBean);
		else 
			flag = getTrainingService().update(trainingBean);
		if(flag){
			if(isCourseCome){
				trainingList = getTrainingService().getCourseAll(chapter_course_id ,type);
			}else{
				courseContentTestList = getCourseContentService().getTestChapterLis(courrCourseId);
				trainingList = getTrainingService().getChapterAll(chapter_course_id);
			}
			return MAIN ;
		}else{
			showMsg("formid", "messages_error_info");
		}
		return "";
	}
	
	
	public String editCourseJob(){
		showErrorMsg = false;
		if(trainingBean.getTraining_contents() == null || trainingBean.getTraining_contents().equals("")){
			showMsg("training_contents", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(trainingBean.getTraining_refrence_answer() == null || trainingBean.getTraining_refrence_answer().equals("")){
			showMsg("training_refrence_answer", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		trainingBean.setIs_chapter(type);
		/**
		 * 表示当前操作是判断题还是选择题
		 * 判断题标示： 1：[选择值0：错误/1：正确]
		 * 选择题标示：0：[A值描述]:[B值描述]:[C值描述]:[D值描述]
		 */
		JSONObject json = new JSONObject();
		json.put("type", trainingBean.getTraining_options_type());
		String optionVal = "" ;
		if(trainingBean.getTraining_options_type().equals("1")){
			//进行值是否选择判断
			if(trainingBean.getTraining_options_judgment() == null || trainingBean.getTraining_options_judgment().equals("")){
				showMsg("options_judgment", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			//判断题
//			optionVal = trainingBean.getTraining_options_type() +":"+trainingBean.getTraining_options_judgment();
//			if(trainingBean.getTraining_options_judgment().equals("0"))
//				trainingBean.setTraining_refrence_answer("B");
//			else
//				trainingBean.setTraining_refrence_answer("A");
		}else{
			//进行值是否选择判断
			if(trainingBean.getTraining_options_select_a() == null || trainingBean.getTraining_options_select_a().equals("")){
				showMsg("training_optionsA", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			if(trainingBean.getTraining_options_select_b() == null || trainingBean.getTraining_options_select_b().equals("")){
				showMsg("training_optionsB", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			if(trainingBean.getTraining_options_select_c() == null || trainingBean.getTraining_options_select_c().equals("")){
				showMsg("training_optionsC", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			if(trainingBean.getTraining_options_select_d() == null || trainingBean.getTraining_options_select_d().equals("")){
				showMsg("training_optionsD", "javax.faces.component.UIInput.REQUIRED");
				return "";
			}
			//选择题
//			optionVal = trainingBean.getTraining_options_type() +":"+trainingBean.getTraining_options_select_a()
//																+":"+trainingBean.getTraining_options_select_b()
//																+":"+trainingBean.getTraining_options_select_c()
//																+":"+trainingBean.getTraining_options_select_d(); 
			json.put("a", trainingBean.getTraining_options_select_a());
			json.put("b", trainingBean.getTraining_options_select_b());
			json.put("c", trainingBean.getTraining_options_select_c());
			json.put("d", trainingBean.getTraining_options_select_d());
		}
		optionVal = json.toString();
		trainingBean.setTraining_options(optionVal);
			
		boolean flag = false; 
		trainingBean.setChapter_course_id(chapter_course_id);
		if(trainingBean.getId() == 0 )
			flag = getTrainingService().sava(trainingBean);
		else 
			flag = getTrainingService().update(trainingBean);
		if(flag){
			if(isCourseCome){
				trainingList = getTrainingService().getCourseAll(chapter_course_id ,type);
			}else{
				courseContentTestList = getCourseContentService().getTestChapterLis(courrCourseId);
				trainingList = getTrainingService().getChapterAll(chapter_course_id);
			}
			return MAIN ;
		}else{
			showMsg("formid", "messages_error_info");
		}
		return "";
	}
	
	
	public String editCourseSurvey(){
		showErrorMsg = false;
		if(trainingBean.getTraining_contents() == null || trainingBean.getTraining_contents().equals("")){
			showMsg("training_contents", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		trainingBean.setIs_chapter(type);
		//进行值是否选择判断
		if(trainingBean.getTraining_options_select_a() == null || trainingBean.getTraining_options_select_a().equals("")){
			showMsg("training_optionsA", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(trainingBean.getTraining_options_select_b() == null || trainingBean.getTraining_options_select_b().equals("")){
			showMsg("training_optionsB", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(trainingBean.getTraining_options_select_c() == null || trainingBean.getTraining_options_select_c().equals("")){
			showMsg("training_optionsC", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(trainingBean.getTraining_options_select_d() == null || trainingBean.getTraining_options_select_d().equals("")){
			showMsg("training_optionsD", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		//选择题
//		String optionVal = trainingBean.getTraining_options_type() +":"+trainingBean.getTraining_options_select_a()
//															+":"+trainingBean.getTraining_options_select_b()
//															+":"+trainingBean.getTraining_options_select_c()
//															+":"+trainingBean.getTraining_options_select_d(); 
		JSONObject  json = new JSONObject();
		json.put("type", trainingBean.getTraining_options_type());
		json.put("a", trainingBean.getTraining_options_select_a());
		json.put("b", trainingBean.getTraining_options_select_b());
		json.put("c", trainingBean.getTraining_options_select_c());
		json.put("d", trainingBean.getTraining_options_select_d());
		trainingBean.setTraining_options(json.toString());
		
		
		boolean flag = false; 
		trainingBean.setChapter_course_id(chapter_course_id);
		if(trainingBean.getId() == 0 )
			flag = getTrainingService().sava(trainingBean);
		else 
			flag = getTrainingService().update(trainingBean);
		if(flag){
			if(isCourseCome){
				trainingList = getTrainingService().getCourseAll(chapter_course_id ,type);
			}else{
				courseContentTestList = getCourseContentService().getTestChapterLis(courrCourseId);
				trainingList = getTrainingService().getChapterAll(chapter_course_id);
			}
			return MAIN ;
		}else{
			showMsg("formid", "messages_error_info");
		}
		return "";
	}
	
	
	public void goDown(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String id = varMap.get("id");
		getTrainingService().goDown(id ,type);
		if(isCourseCome)
			trainingList = getTrainingService().getCourseAll(chapter_course_id,type);
		else
			trainingList = getTrainingService().getChapterAll(chapter_course_id);
	}
	public void goUp(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String id = varMap.get("id");
		getTrainingService().goUp(id , type);
		if(isCourseCome)
			trainingList = getTrainingService().getCourseAll(chapter_course_id,type);
		else
			trainingList = getTrainingService().getChapterAll(chapter_course_id);
	}
	
	public String showChapterList(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String id = varMap.get("id");
		courrCourseId = Integer.parseInt(id);
		courseContentTestList = getCourseContentService().getTestChapterLis(Integer.parseInt(id));
		
		TraningScoreBean bean = getTrainingService().checkTraningScoreIsSubmit(type,chapter_course_id);
		traningTotalScore = bean.getTotalScore() ;
		traningCurrTotalScore = bean.getTraningScore();
		return "chapter";
	}
	
	public String showCourseTraining(){
		isCourseCome = true ;
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		chapter_course_id = varMap.get("id");
		type = varMap.get("type");
		trainingList = getTrainingService().getCourseAll(chapter_course_id ,type);
		TraningScoreBean bean = getTrainingService().checkTraningScoreIsSubmit(type,chapter_course_id);
		
		
		traningTotalScore = bean.getTotalScore();
		traningCurrTotalScore = bean.getTraningScore();
		showAddButton = false;
		if(type.equals("1")){
			if(traningTotalScore == bean.getTraningScore())
				showAddButton = true ;
			else
				showAddButton = false ;
			return "training";
		}else if(type.equals("2")){
			return "job";
		}else if(type.equals("3")){
			return "survey";
		}
		return "";
	}
	
	
	
	public String importCourseTraing(){
		
		String savePath = CCPContants.SYS_PATH+"files"+File.separator + "courseTraning" + File.separator + CCPContants.getUserBean().getId() + File.separator;
		File[] f1 = new File(savePath).listFiles();
		if(f1 == null || f1.length <= 0){
			showMsg("uploadStudent", "course_page_course_submit_error_8");
			return "";
		}
		for(File f:f1)
			importFileForStudent(f);
		trainingList = getTrainingService().getCourseAll(chapter_course_id ,type);
		return MAIN;
	}
	
	
	
	private void importFileForStudent(File file){
		Sheet sheet;
        Workbook book;
        try{
        	Map<String ,String> keyValueMap = new HashMap<String, String>(); 
        	book = Workbook.getWorkbook(file); 
        	sheet = book.getSheet(0);
        	//从第五行开始读取数据，前面四行预留
        	int allLines = sheet.getRows();
        	int count = getTrainingService().getCourseAll(chapter_course_id ,type).size();
        	
        	for(int i=4;i<allLines;i++){
        		count = count + 1 ;
        		TrainingBean bean = new TrainingBean();
        		
        		bean.setChapter_course_id(chapter_course_id);//这里是填写 course_setting id值
        		bean.setTraining_no(""+count);
        		bean.setIs_chapter(type);
        		bean.setTraining_contents(sheet.getCell(1, i).getContents());
        		bean.setTraining_score(sheet.getCell(2, i).getContents());
        		bean.setTraining_refrence_answer(sheet.getCell(3, i).getContents());
        		String a = sheet.getCell(4, i).getContents() ;
        		String b = sheet.getCell(5, i).getContents() ;
        		String c = sheet.getCell(6, i).getContents() ;
        		String d = sheet.getCell(7, i).getContents() ;
        		
        		String type = sheet.getCell(0, i).getContents() ;
        		JSONObject json = new JSONObject();
        		if(type.equals("判断题")){
        			json.put("type", 1);
        		}else if(type.equals("选择题")){
        			json.put("type", 0);
        		}
        		json.put("a", a);
        		json.put("b", b);
        		json.put("c", c);
        		json.put("d", d);
        		bean.setTraining_options(json.toString());
        		
        		getTrainingService().sava(bean);
        	}
        	
        	TraningScoreBean bean = getTrainingService().checkTraningScoreIsSubmit(type,chapter_course_id);
        	traningTotalScore = bean.getTotalScore();
    		traningCurrTotalScore = bean.getTraningScore();
    		if(traningCurrTotalScore > traningTotalScore ){
    			traningTotalScore = traningCurrTotalScore ;
    			showAddButton = true ;
    		}
        	CourseSettingBean csb = getCourseService().getCourseSetingBean(chapter_course_id);
        	csb.setScore(""+traningCurrTotalScore) ;
        	getCourseService().updateCourseSetting(csb);
        	
        }catch(Exception e){
        	file.delete();
        }
	}
	
	
	
	
	public String showCourseSurvey(){
		isCourseCome = true ;
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		chapter_course_id = varMap.get("id");
		type = varMap.get("type");
		trainingList = getTrainingService().getCourseAll(chapter_course_id ,type);
		TraningScoreBean bean = getTrainingService().checkTraningScoreIsSubmit(type,chapter_course_id);
		traningTotalScore = bean.getTotalScore() ;
		traningCurrTotalScore = bean.getTraningScore();
		if(bean.getTotalScore() == bean.getTraningScore())
			showAddButton = true ;
		else
			showAddButton = false ;
		
		return "survey";
	}
	
	
	
	
	public String showChapterTraining(){
		isCourseCome = false ;
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		chapter_course_id = varMap.get("id");
		trainingList = getTrainingService().getChapterAll(chapter_course_id);
		
		TraningScoreBean bean = getTrainingService().checkTraningScoreIsSubmit(type,chapter_course_id);
		traningTotalScore = bean.getTotalScore() ;
		traningCurrTotalScore = bean.getTraningScore();
		if(bean.getTotalScore() == bean.getTraningScore())
			showAddButton = true ;
		else
			showAddButton = false ;
		return "training";
	}
	
	public String edit(){
		return null;
	}
	
	public String trainingGoBack(){
		if(isCourseCome)
			return "gobackCourse" ;
		else
			return "gobackChapter";
	}
	
	

	@Override
	public void getpagedetail() {
		setItemCount(getCourseService().getTestCount());
		int currentpage = getCurrentPage();
		int pagesize = getPageSize();
		int start = (currentpage - 1) * pagesize;
		courseTestList = getCourseService().getTestCourseList(start, pagesize);
	}


	public List<CourseBean> getCourseTestList() {
		getpagedetail();
		return courseTestList;
	}


	public void setCourseTestList(List<CourseBean> courseTestList) {
		this.courseTestList = courseTestList;
	}


	public List<CourseContentBean> getCourseContentTestList() {
		if(courseContentTestList == null)
			courseContentTestList = new ArrayList<CourseContentBean>();
		return courseContentTestList;
	}


	public void setCourseContentTestList(List<CourseContentBean> courseContentTestList) {
		this.courseContentTestList = courseContentTestList;
	}

	
	private boolean deleteAll;//全部删除标志
	
	public String doDeleteAll(){
		log.info("-------------chapter_course_id = "+chapter_course_id);
		for(TrainingBean b : trainingList){
			if(b.isWillDelete()){
				log.info("====delete train "+b);
				getTrainingService().delete(b.getId());
			}
		}
		trainingList = getTrainingService().getCourseAll(chapter_course_id,"1");
		return "";
	}

	public boolean isDeleteAll() {
		return deleteAll;
	}
	public void setDeleteAll(boolean deleteAll) {
		this.deleteAll = deleteAll;
	}
	public String doSelectAllForDelete(){
		log.info("-----------------deleteAll = "+deleteAll);
		for(TrainingBean b : trainingList)
			b.setWillDelete(deleteAll);
		return "";
	} 
	
	
	public List<TrainingBean> getTrainingList() {
		if(trainingList == null)
			trainingList = new ArrayList<TrainingBean>();
		return trainingList;
	}


	public void setTrainingList(List<TrainingBean> trainingList) {
		this.trainingList = trainingList;
	}


	public TrainingBean getTrainingBean() {
		if(trainingBean == null)
			trainingBean = new TrainingBean();
		return trainingBean;
	}


	public void setTrainingBean(TrainingBean trainingBean) {
		this.trainingBean = trainingBean;
	}
	public boolean isCourseCome() {
		return isCourseCome;
	}
	public void setCourseCome(boolean isCourseCome) {
		this.isCourseCome = isCourseCome;
	}
	public String getChapter_course_id() {
		return chapter_course_id;
	}
	public void setChapter_course_id(String chapter_course_id) {
		this.chapter_course_id = chapter_course_id;
	}
	public int getTraningCurrTotalScore() {
		return traningCurrTotalScore;
	}
	public void setTraningCurrTotalScore(int traningCurrTotalScore) {
		this.traningCurrTotalScore = traningCurrTotalScore;
	}
	public int getTraningTotalScore() {
		return traningTotalScore;
	}
	public void setTraningTotalScore(int traningTotalScore) {
		this.traningTotalScore = traningTotalScore;
	}
	public boolean isShowErrorMsg() {
		return showErrorMsg;
	}
	public void setShowErrorMsg(boolean showErrorMsg) {
		this.showErrorMsg = showErrorMsg;
	}
	public boolean isShowAddButton() {
		return showAddButton;
	}
	public void setShowAddButton(boolean showAddButton) {
		this.showAddButton = showAddButton;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
}
